import {
  reqDeleteShopCart,
  reqShopCartList,
  reqUpdateCheckedById,
} from "@/api";

const actions = {
  async shopCartList({ commit }) {
    let result = await reqShopCartList();
    console.log("ShopCartList", result.data);
    if (result.code == 200) {
      commit("ShopCartList", result.data);
    }
  },
  // eslint-disable-next-line no-unused-vars
  async deleteShopCart({ commit }, skuId) {
    let result = await reqDeleteShopCart(skuId);
    // console.log('ShopCartList',result.data);
    if (result.code == 200) {
      return "OK";
    } else {
      return Promise.reject(new Error("Failed!"));
    }
  },
  // eslint-disable-next-line no-unused-vars
  async updateIsCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("Failed!"));
    }
  },
  /**
   * (1)注意actions中的context这个上下文对象包含了很多东西，包括：dispatch、commit、state、getters
   *    这么看来context其实就是为了 方便相互调用函数吧
   * (2) Promise.all()里面放一个数组，数组放promise对象，它可以返回所有promise综合结果
   *     全部为成功才为成功，否则只要有一个不成功就失败
   * */
  deleteAllCheckedCarts({ dispatch, getters }) {
    let promiseAll = [];
    getters.cartList.cartInfoList.forEach((item) => {
      let promise =
        item.isChecked == 1 ? dispatch("deleteShopCart", item.skuId) : "";
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
  updateAllIsChecked({ dispatch, getters },isChecked) {
    let promiseAll = [];
    getters.cartList.cartInfoList.forEach((item) => {
      let promise = dispatch("updateIsCheckedById", {skuId:item.skuId,isChecked});
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
};

const mutations = {
  ShopCartList(state, shopCartList) {
    state.shopCartList = shopCartList;
  },
};

// 对于想要的数据层数太多，就需要在getters里面准备好，而且还要考虑到没请求到数据的情况
const getters = {
   cartList(state){
       return state.shopCartList[0]||{}
   }
};

const state = {
  shopCartList: [],
};

export default {
  actions,
  mutations,
  getters,
  state,
};
